<template>
  <div class="upload">
    <el-upload
      class="avatar-uploader"
      :action="apiUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :on-error="handleAvatarError"
      :before-upload="beforeAvatarUpload"
      :headers="headers"
    >
      <img v-if="imageUrl" :src="imageUrl | filePath" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
<script>
import { environment } from '../../models/environment';
import axios from 'axios';
import { getItem } from '../../script/config/common'
export default {
  name: 'ImageUpload',
  props: ['url'],
  data() {
    return {
      imageUrl: '',
      apiUrl: environment.API_URL + '/service/fileUpload',
      headers: {}
    }
  },
  watch: {
    url(val) {
      this.imageUrl = val
    },
    imageUrl(val) {
      this.$emit('update:url', val)
    }
  },
  computed: {

  },
  mounted() {
    let user = getItem('user');
    let token = getItem('token');

    if (user) {
      this.headers.user = user.SysUserId;
      this.headers.purview = (user.PurviewGroupIds || []).join(',');
    }
    if (token) {
      this.headers.authorization = token.token || {};
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log("handleAvatarSuccess -> file", file)
      console.log("handleAvatarSuccess -> res", res)
      this.imageUrl = res.fname;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },

    handleAvatarError(err, file, fileList) {
      this.$message.warning('上传失败' || err.message)
    },

    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 5;

      // if (!isJPG) {
      //   this.$message.warning('上传图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.warning('上传图片大小不能超过 5MB!');
      }
      return isLt2M;
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
